/*
 *    Thing Game Library
 *   Copyright (C)2005 - 2010 Eduardo Nunes Pereira (eduardonunesp at gmail dot com)
 *
 *   This program/library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 *   This program/library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 *    You should have received a copy of the GNU Lesser General Public
 * License along with this program/library ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "xml.hpp"
#include <fstream>
#include <cstring>
#include <iostream>
#include "resourcemanager.hpp"
#include "logger.hpp"


namespace XML
{
    Document::Document(const std::string &file_name, bool use_resman):
        mDoc(0)
    {   
        int size;
        char *data = NULL;
        if (use_resman) {   
            ResourceManager *resman = ResourceManager::getInstance();
            data = (char*) resman->loadFile(file_name.c_str(), size);
        } else {   
            std::ifstream file;
            file.open(file_name.c_str(), std::ios::in);

            if (file.is_open()) {   
                /* Get length of file */
                file.seekg (0, std::ios::end);
                size = file.tellg();
                file.seekg(0, std::ios::beg);

                data = (char*) malloc(size);

                file.read(data, size);
                file.close();
            } else {   
                Logger::getInstance()->log("Error loading XML file %s", file_name.c_str());
            }   
        }   

        if (data) {   
            mDoc = xmlParseMemory(data, size);
            free(data);

            if (!mDoc)
                Logger::getInstance()->log("Error parsing XML file %s", file_name.c_str());
        } else {   
            Logger::getInstance()->log("Error loading %s", file_name.c_str());
        }   
    }   

    Document::Document(const char *data, int size)
    {   
        mDoc = xmlParseMemory(data, size);
    }   
}
